"""
cron: 0 */2 * * *
new Env('空气质量采集');
"""

import requests
import os
import mysql.connector
from datetime import datetime

def get_db_config():
    """获取数据库配置"""
    try:
        host = os.environ.get('HOST')
        user = os.environ.get('USER')
        password = os.environ.get('PASSWORD')
        database = os.environ.get('DATABASE')
        weather_key = os.environ.get('QWEATHER_KEY')
        
        print("正在获取环境变量...")
        print(f"数据库地址：{host}")
        print(f"数据库用户名：{user}")
        print(f"数据库密码：{password}")
        print(f"数据库名称：{database}")
        
        if not all([host, user, password, database, weather_key]):
            raise ValueError("环境变量不完整")
            
        return host, user, password, database, weather_key
    except Exception as e:
        print(f"获取配置失败: {str(e)}")
        raise

def get_air_quality(api_key, city_name):
    """获取城市空气质量数据"""
    try:
        # 先获取城市ID
        location_url = "https://geoapi.qweather.com/v2/city/lookup"
        params = {
            'location': city_name,
            'key': api_key
        }
        
        response = requests.get(location_url, params=params)
        location_data = response.json()
        
        if location_data['code'] != '200':
            raise ValueError(f"未找到城市: {city_name}")
            
        city_id = location_data['location'][0]['id']
        
        # 获取空气质量数据
        air_url = "https://api.qweather.com/v7/air/now"
        params = {
            'location': city_id,
            'key': api_key
        }
        
        response = requests.get(air_url, params=params)
        air_data = response.json()
        
        if air_data['code'] == '200':
            now = air_data['now']
            return {
                'city': city_name,
                'aqi': now['aqi'],
                'category': now['category'],
                'pm2p5': now['pm2p5'],
                'pm10': now['pm10'],
                'create_time': datetime.now()
            }
            
    except Exception as e:
        print(f"获取空气质量数据失败: {str(e)}")
        return None

def main():
    try:
        # 获取配置
        host, user, password, database, weather_key = get_db_config()
        
        # 连接数据库
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )
        
        cursor = connection.cursor()
        
        # 监测城市列表
        cities = ['北京', '上海', '广州', '深圳']
        
        for city in cities:
            air_data = get_air_quality(weather_key, city)
            if air_data:
                # 删除旧数据
                delete_query = "DELETE FROM ningm_air_quality WHERE city = %s"
                cursor.execute(delete_query, (city,))
                
                # 插入新数据
                insert_query = """
                    INSERT INTO ningm_air_quality 
                    (city, aqi, category, pm2p5, pm10, create_time) 
                    VALUES (%s, %s, %s, %s, %s, %s)
                """
                insert_values = (
                    air_data['city'],
                    air_data['aqi'],
                    air_data['category'],
                    air_data['pm2p5'],
                    air_data['pm10'],
                    air_data['create_time']
                )
                cursor.execute(insert_query, insert_values)
                print(f"成功保存{city}的空气质量数据")
        
        connection.commit()
        cursor.close()
        connection.close()
        
    except Exception as e:
        print(f"程序执行失败: {str(e)}")

if __name__ == "__main__":
    main() 